/*
 * Copyright (c) 2009 VMware, Inc.
 * Copyright (c) 2009 John Pritchard, WTKX Project Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package wtkx.co;

import wtkx.Component;
import wtkx.io.UrlcInputStream;

import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.Iterator;
import javax.imageio.ImageIO;

/**
 * Resource cache dictionary implementation.
 *
 * @author gbrown
 * @author jdp
 */
public final class ResourceCacheDictionary
    extends java.util.HashMap<URL, Object>
    implements jbxml.Dictionary<URL, Object>, Iterable<URL> 
{


    public ResourceCacheDictionary(){
        super();
    }

    public Object get(URL key) {
        return super.get(key);
    }
    public Object remove(URL key) {
        return super.remove(key);
    }
    public boolean containsKey(URL key) {
        return super.containsKey(key);
    }
    public BufferedImage getImage(Component c, URL u){
        BufferedImage cached = (BufferedImage)this.get(u);
        if (null == cached){
            try {
                UrlcInputStream in = c.reader(c,u.openConnection());
                if (null != in){
                    try {
                        cached = ImageIO.read(in);
                        this.put(u,cached);
                    }
                    finally {
                        in.close();
                    }
                }
            }
            catch (Exception exc){
                exc.printStackTrace();
            }
        }
        return cached;
    }
    public void loadImages(Component c, URL[] list){
        for (URL u : list){
            this.getImage(c,u);
        }
    }

    public Iterator<URL> iterator() {
        return super.keySet().iterator();
    }
}
